from gov.serializers import GovCourseListSerializer, SatCourseListSerializer
from time import time
from ability.serializer.serializers import ChapterListSerializer, ChapterSerializer, CourseListSerializer, CourseSerializer
from study.utils import rand_str
from ability.excepts import LogicException
from ability.models import Chapter, Course, Gov, GovCourse, GovUser, GovCourseView, GovUser, Sms, Student, UserProfile
from ability.format import CustomResponse, GetPostParaOrNone
import traceback
from rest_framework.response import Response
from ability.enums import ErrorCode

from rest_framework.views import APIView

# Create your views here.
class Login(APIView):

	def post(self, request, *args, **kwargs):
		try:
			self.response_format = CustomResponse().response
			phone =  GetPostParaOrNone(request.data, 'phone')
			code =  GetPostParaOrNone(request.data, 'code')
			verifyCode = GetPostParaOrNone(self.request.data, 'verifyCode')

			if phone is None or code is None:
				raise LogicException("参数不正确")

			if Sms.verify(phone, verifyCode) == False:
				raise LogicException('短信验证码不正确')
			
			user = UserProfile.objects.filter(phone=phone).first()
			if user is None:
				# todo register student
				user = UserProfile.addOne(phone, phone, 'S', phone=phone)

			gov = Gov.getByCode(code)
			if gov is None:
				raise LogicException("手机号或听课码不正确")

			govUser = GovUser.getOne(gov=gov, user=user)
			if govUser is None:
				govUser = GovUser.addOne(gov=gov, user=user)
			else:
				govUser.tk = rand_str(60)
				govUser.save()
			
			self.response_format['data'] = {
				'tk': govUser.tk
			}
			
			return Response(self.response_format)
		except LogicException as e:
			self.response_format['error_code'] = ErrorCode.parameter_error.value
			self.response_format['message'] = str(e)
		except Exception as e:
			traceback.print_exc()
			self.response_format['error_code'] = ErrorCode.comon_error.value
			self.response_format['message'] = '服务器异常'
		return Response(self.response_format)
	
class CourseView(APIView):

	def post(self, request, *args, **kwargs):
		try:
			self.response_format = CustomResponse().response
			tk =  GetPostParaOrNone(request.data, 'tk')
			govUser = GovUser.getByTk(tk)
			if govUser is None:
				self.response_format['error_code'] = ErrorCode.auth_error.value
				self.response_format['message'] = "未登录"
				return Response(self.response_format)
			
			course_id =  GetPostParaOrNone(request.data, 'course_id')
			if course_id is None:
				self.response_format['error_code'] = ErrorCode.auth_error.value
				self.response_format['message'] = "课程不存在"
				return Response(self.response_format)

			course = Course.getById(course_id)
			if course is None or course.status != 'N':
				self.response_format['error_code'] = ErrorCode.auth_error.value
				self.response_format['message'] = "课程不存在"
				return Response(self.response_format)

			gov_course = GovCourse.getOne(course, govUser.gov)
			if gov_course is None:
				raise LogicException("课程未授权")

			chapter = ChapterListSerializer(Chapter.get_by_course(course), many=True)
			act_chapter = None
			act_chapter_model = None
			chapter_id = GetPostParaOrNone(request.data, 'chapter_id')
			play_time = 0 # 已经播放时间
			point_ts = 0
			if chapter_id not in ['', None]:
				chapter_id = GetPostParaOrNone(request.data, 'chapter_id')
				act_chapter_model = Chapter.get_by_id(chapter_id)
				act_chapter = ChapterSerializer(act_chapter_model)
			else:
				act_chapter_model = Chapter.objects.filter(course=course).first()
				act_chapter =  ChapterSerializer(act_chapter_model)
			if act_chapter_model is not None:
				act_chapter_model.pv += 1
				act_chapter_model.save()
				play_time = GovCourseView.getViewTime(act_chapter_model, govUser.gov, govUser.user)
				point_ts = GovCourseView.getLastPointTs(act_chapter_model, govUser.gov, govUser.user)

			self.response_format['data'] = {
				'chapters': chapter.data,
				'act_chapter': act_chapter.data,
				'play_time': play_time,
				'course': CourseSerializer(course).data,
				'point_ts': point_ts
			}

			return Response(self.response_format)
		except LogicException as e:
			self.response_format['error_code'] = ErrorCode.parameter_error.value
			self.response_format['message'] = str(e)
		except Exception as e:
			traceback.print_exc()
			self.response_format['error_code'] = ErrorCode.comon_error.value
			self.response_format['message'] = '服务器异常'
		return Response(self.response_format)
	
class CourseList(APIView):
	def post(self, request, *args, **kwargs):
		try:
			self.response_format = CustomResponse().response
			tk =  GetPostParaOrNone(request.data, 'tk')
			if tk is None:
				self.response_format['error_code'] = ErrorCode.auth_error.value
				return Response(self.response_format)

			gu = GovUser.getByTk(tk)
			if gu is None:
				self.response_format['error_code'] = ErrorCode.auth_error.value
				return Response(self.response_format)

			gov_courses = GovCourse.getByGov(gu.gov)

			self.response_format['data'] = {
				'courses': GovCourseListSerializer(gov_courses, many=True).data
			}
			return Response(self.response_format)
		except LogicException as e:
			self.response_format['error_code'] = ErrorCode.parameter_error.value
			self.response_format['message'] = str(e)
		except Exception as e:
			traceback.print_exc()
			self.response_format['error_code'] = ErrorCode.comon_error.value
			self.response_format['message'] = '服务器异常'
		return Response(self.response_format)

class CoursePlay(APIView):

	def post(self, request, *args, **kwargs):
		try:
			self.response_format = CustomResponse().response
			tk =  GetPostParaOrNone(request.data, 'tk')
			govUser = GovUser.getByTk(tk)
			if govUser is None:
				# todo logout 
				raise LogicException("课程不存在")
			chapter_id = GetPostParaOrNone(request.data, 'chapter_id')
			point_ts = GetPostParaOrNone(request.data, 'point_ts', 0)
			chapter = Chapter.get_by_id(chapter_id)
			if chapter is None:
				raise LogicException("章节不存在")

			gcv = GovCourseView.getOne(chapter, govUser.gov, govUser.user)

			if gcv is None:
				GovCourseView.addOne(chapter, govUser.gov,  govUser.user, point_ts)
			else:
				ts = int(time())
				print("ts", ts, "last ts", gcv.last_ts, ts - gcv.last_ts)

				if ts - gcv.last_ts > 3:
					GovCourseView.addOne(chapter,  govUser.gov,  govUser.user, point_ts)
				else:
					gcv.last_ts = ts
					gcv.point_ts = point_ts
					gcv.save()

			play_time = GovCourseView.getViewTime(chapter, govUser.gov, govUser.user)
			self.response_format['data'] = {
				'play_time': play_time,
			}

			return Response(self.response_format)
		except LogicException as e:
			self.response_format['error_code'] = ErrorCode.parameter_error.value
			self.response_format['message'] = str(e)
		except Exception as e:
			traceback.print_exc()
			self.response_format['error_code'] = ErrorCode.comon_error.value
			self.response_format['message'] = '服务器异常'
		return Response(self.response_format)

	
	